/* global window */
import pathToRegexp from 'path-to-regexp'
import { message } from 'antd'
import { routerRedux } from 'dva/router'
import { info } from 'services/project'
import { add, update, remove } from 'services/field'

export default {
  namespace: 'projectConfig',

  state: {
    project: {},
    currentItem: [],
    modalVisible: false,
    resetModalVisible: false,
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/project/:id/config').exec(location.pathname)
        if (match) {
          dispatch({ type: 'info', payload: { id: match[1] } })
        }
      })
    },
  },

  effects: {

    * info ({ payload = {} }, { call, put }) {
      const { success, data, errorMsg } = yield call(info, payload)
      if (success) {
        yield put({
          type: 'updateState',
          payload: {
            project: data,
          },
        })
      } else {
        throw errorMsg
      }
    },

    * save ({ payload }, { select, call, put }) {
      const projectConfig = yield select(_ => _.projectConfig)
      const { project } = projectConfig
      payload.projectId = project.id
      const data = yield call(payload.id ? update : add, payload)
      if (data.success) {
        message.success(payload.id ? '更新成功' : '添加成功')
        yield put({ type: 'info', payload: { id: project.id } })
        yield put({ type: 'hideModal' })
      } else {
        throw data.errorMsg
      }
    },

    * remove ({ payload }, { select, call, put }) {
      const projectConfig = yield select(_ => _.projectConfig)
      const { project } = projectConfig
      payload.projectId = project.id
      const data = yield call(remove, payload)
      if (data.success) {
        message.success('删除成功')
        yield put({ type: 'info', payload: { id: project.id } })
        yield put({ type: 'hideModal' })
      } else {
        throw data.errorMsg
      }
    },
  },

  reducers: {

    updateState (state, { payload }) {
      return { ...state, ...payload }
    },

    showModal (state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal (state) {
      return { ...state, modalVisible: false, currentItem: {} }
    },

    showResetModal (state, { payload }) {
      return { ...state, ...payload, resetModalVisible: true }
    },

    hideResetModal (state) {
      return { ...state, resetModalVisible: false }
    },
  },
}
